<?php

namespace App\Http\Controllers\Rent;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class AliController extends Controller
{
    public function notify(){
    	require_once  '../payment/AopClient.php';
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAokOXGvXftJldmPxFqTJAvKH9bPoR9MAueiRqdUWpY1H6V8V1aUEf8VJvS/TK5BQi7p2ZCtqfmA/KWCg/LHy09HmnTvp+Ahv2hvFMLrvgHFVD9dDVJ4kG5J4/hZq+ISJt8fM8uJnXswoGX83XJffSK4ISkHA8JdQwEXljsMu+WK+xZNyiZ6fx9EMTghzolbT+PR+h45t7vzFiKEMCW2rj6ZLjWkW3w2PmppPmzqMK1bWRhmqfqtUZVi5v5eTFOdLCUY5xnMNUGSNmcGgkiIZT/i1kqe1ggUbIpG2bbHR8ZMowYgHIUObSRG25xkwgSpVZDuRoDlBtsSUZap/mqkIecQIDAQAB';
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag){
        	// resultLog('wen.alipay.log',json_encode($_POST));
        	//商户订单号

        	$out_trade_no = $_POST['out_trade_no'];
        	$class = $_POST['subject'];
        	$price = $_POST['total_amount'];
			//支付宝交易号

			$trade_no = $_POST['trade_no'];
        	if($_POST['trade_status'] == 'TRADE_FINISHED') {

				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//请务必判断请求时的total_amount与通知时获取的total_fee为一致的
					//如果有做过处理，不执行商户的业务程序
						
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
		    }
		    else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//请务必判断请求时的total_amount与通知时获取的total_fee为一致的
					//如果有做过处理，不执行商户的业务程序			
				//注意：
				//付款完成后，支付宝系统发送该交易状态通知
				DB::table('paylog')->where('order',$out_trade_no)->update(array('token'=>$trade_no,'status'=>1));
				$paylog = (array)DB::table('paylog')->where('order',$out_trade_no)->first();
				$uid = $paylog['uid'];
				$fid = $paylog['fid'];
				if('查看会员'==$class){
					$uidInfo = (array)DB::table('members')->select('weixin','money')->where('id',$uid)->first();
					$money = ($uidInfo['money']*100+$price*100)/100;
					$wx = $uidInfo['weixin'];
					$data = array(
						'uid'=>$uid,
						'fid'=>$fid,
						'wx'=>$wx,
						'create_time'=>time()
					);
					DB::table('seewx')->insert($data);
					DB::table('members')->where('id',$uid)->update(array('money'=>$money));
				}else if('充值' == $class){
					DB::update("update ims_members set money = money + {$price} where id = {$uid}");
				}

		    }
        	echo "success";		//请不要修改或删除
        }else{
        	//验证失败
    		echo "fail";	//请不要修改或删除
        }
        
    }

    public function alipay(){
	    $data = array();
	    if(!empty($_POST['price'])){
	        $data['price'] = $_POST['price'];
	    }else{
	        return json_encode(array('r'=>-1,'msg'=>'没有传入金额'));
	    }
	    if(!empty($_POST['type'])){
	        $data['type'] = $_POST['type'];
	    }else{
	        return json_encode(array('r'=>-1,'msg'=>'没有传入支付方式'));
	    }
	    
	    if(!empty($_POST['class'])){
	        $data['class'] = $_POST['class'];
	    }else{
	        return json_encode(array('r'=>-1,'msg'=>'没有传入支付说明'));
	    }

	    if($data['class'] == '充值'){
	    	if(!empty($_POST['uid'])){
	    		$data['uid'] = $_POST['uid'];
	    	}else{
	    		return json_encode(array('r'=>-1,'msg'=>'充值-uid不存在!'));
	    	}
	    	
	    }else if($data['class'] == '消费' || $data['class'] == '查看会员'){
	    	if(!empty($_POST['uid']) && !empty($_POST['fid'])){
	    		$data['uid'] = $_POST['uid'];
    			$data['fid'] = $_POST['fid'];
	    	}else{
	    		return json_encode(array('r'=>-1,'msg'=>'消费或查看会员-uid/fid不存在!'));
	    	}
	    }


	    $data['order'] = date('Ymdhis',time()).rand(100,200);
	    $data['create_time'] = time();
	    $bool = DB::table('paylog')->insert($data);
		require_once  '../payment/AopClient.php';
		require_once  '../payment/AlipayTradeAppPayRequest.php';
	    require_once  '../payment/config.php';
        $aop = new \AopClient;
        $aop->gatewayUrl = $config['gatewayUrl'];
        $aop->appId = $config['app_id'];
        $aop->rsaPrivateKey = $config['rsaPrivateKey'];
        $aop->format = $config['format'];
        $aop->charset = $config['charset'];
        $aop->signType = $config['sign_type'];
        $aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'];
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = "{\"body\":\"".$data['class']."\","
            . "\"subject\": \"".$data['class']."\","
            . "\"out_trade_no\": \"".$data['order']."\","
            . "\"timeout_express\": \"30m\"," 
            . "\"total_amount\": \"".$data['price']."\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        $request->setNotifyUrl($config['notify_url']);
        $request->setBizContent($bizcontent);
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        // echo htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
        return json_encode(array('r'=>1,'result'=>$response));
    }


    //交易查询接口
    public function aliQuery(){
    	require_once  '../payment/AopClient.php';
		require_once  '../payment/AlipayTradeQueryRequest.php';
    	require_once  '../payment/config.php';
    	$out_trade_no = $_POST['out_trade_no'];
    	$trade_no = $_POST['trade_no'];
    	$aop = new \AopClient ();
		$aop->gatewayUrl = $config['gatewayUrl'];
		$aop->appId = $config['app_id'];
		$aop->rsaPrivateKey = $config['rsaPrivateKey'];
		$aop->alipayrsaPublicKey=$config['alipayrsaPublicKey'];
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='UTF-8';
		$aop->format='json';
		$request = new \AlipayTradeQueryRequest ();
		$request->setBizContent("{" .
		"\"out_trade_no\":\"".$out_trade_no."\"," .
		"\"trade_no\":\"".$trade_no."\"" .
		"  }");
		$result = $aop->execute ( $request);
		return json_encode($result);
    }

    //退款查询接口
    public function aliRefundQuery(){
    	require_once  '../payment/AopClient.php';
    	require_once  '../payment/config.php';
    	require_once  '../payment/AlipayTradeFastpayRefundQueryRequest.php';
    	$out_trade_no = $_POST['out_trade_no'];
    	$aop = new \AopClient ();
		$aop->gatewayUrl = $config['gatewayUrl'];
		$aop->appId = $config['app_id'];
		$aop->rsaPrivateKey = $config['rsaPrivateKey'];
		$aop->alipayrsaPublicKey= $config['alipayrsaPublicKey'];
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='UTF-8';
		$aop->format='json';
		$request = new \AlipayTradeFastpayRefundQueryRequest ();
		$request->setBizContent("{" .
		// "\"trade_no\":\"20150320010101001\"," .
		"\"out_trade_no\":\"".$out_trade_no."\"," .
		"\"out_request_no\":\"".$out_trade_no."\"" .
		"  }");
		$result = $aop->execute ( $request); 

		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->code;
		dump($result);
		if(!empty($resultCode)&&$resultCode == 10000){
		echo "成功";
		} else {
		echo "失败";
		}
    }

    //退款接口
    public function aliRefund(){
		require_once  '../payment/AopClient.php';
		require_once  '../payment/config.php';
		require_once  '../payment/AlipayTradeRefundRequest.php';
		$out_trade_no = $_POST['out_trade_no'];
		$trade_no = $_POST['trade_no'];
		$price = $_POST['price'];
    	$aop = new \AopClient ();
		$aop->gatewayUrl = $config['gatewayUrl'];
		$aop->appId = $config['app_id'];
		$aop->rsaPrivateKey = $config['rsaPrivateKey'];
		$aop->alipayrsaPublicKey= $config['alipayrsaPublicKey'];
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='UTF-8';
		$aop->format='json';
		$request = new \AlipayTradeRefundRequest ();
		$request->setBizContent("{" .
		"\"out_trade_no\":\"".$out_trade_no."\"," .
		// "\"trade_no\":\"".$trade_no."\"," .
		"\"refund_amount\":".$price."," .
		// "\"refund_currency\":\"USD\"," .
		"\"refund_reason\":\"正常退款\"," .
		// "\"out_request_no\":\"HZ01RF001\"," .   //如需部分退款，则此参数必传
		"\"operator_id\":\"OP001\"," .
        "\"store_id\":\"NJ_S_001\"," .
        "\"terminal_id\":\"NJ_T_001\"" .
		"  }");
		$result = $aop->execute($request);
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->code;
		dump($result);
		if(!empty($resultCode)&&$resultCode == 10000){
		echo "成功";
		} else {
		echo "失败";
		}
    }

    //钱包支付
    public function walletPay(){
    	$data = array();
    	if(!empty($_POST['price'])){
	        $data['price'] = $_POST['price'];
	    }else{
	        return json_encode(array('r'=>-1,'msg'=>'没有传入金额'));
	    }

    	$data['order'] = date('Ymdhis',time()).rand(100,200);
	    
	    if(!empty($_POST['class'])){
	        $data['class'] = $_POST['class'];
	    }else{
	        return json_encode(array('r'=>-1,'msg'=>'没有传入支付说明'));
	    }

	    if($data['class'] == '消费' || $data['class'] == '查看会员'){
	    	if(!empty($_POST['uid']) && !empty($_POST['fid'])){
	    		$data['uid'] = $_POST['uid'];
    			$data['fid'] = $_POST['fid'];
	    	}else{
	    		return json_encode(array('r'=>-1,'msg'=>'消费或查看会员-uid/fid不存在!'));
	    	}
	    	
	    }else if($data['class'] == '开通会员'){
	    	if(!empty($_POST['fid'])){
	    		$data['fid'] = $_POST['fid'];
	    	}else{
	    		return json_encode(array('r'=>-1,'msg'=>'开通会员-fid不存在!'));
	    	}
	    	
	    }

	    
	    if(!empty($_POST['type'])){
	        $data['type'] = $_POST['type'];
	    }else{
	        return json_encode(array('r'=>-1,'msg'=>'没有传入支付方式'));
	    }

	    $log = (array)DB::table('members')->select('money','vip')->where('id',$data['fid'])->first();
	    $money = $log['money'];
	    if($money < $data['price']){
	    	return json_encode(array('r'=>-1,'钱包余额不足！'));
	    }
	    $data['create_time'] = time();
	    $bool = DB::table('paylog')->insert($data);
	    $money = ($money*100 - $data['price']*100)/100;
	 	if($data['class'] == '开通会员'){

	 		if($log['vip'] <= time()){
 				if($data['price'] == 0.01){
	 				$time = strtotime("+1 month",time());
		 		}else if($data['price'] == 0.03){
					$time = strtotime("+3 month",time());
		 		}else if($data['price'] == 0.06){
					$time = strtotime("+6 month",time());
		 		}else if($data['price'] == 0.12){
					$time = strtotime("+12 month",time());
		 		}
 			}else{
 				if($data['price'] == 0.01){
	 				$time = strtotime("+1 month",$log['vip']);
		 		}else if($data['price'] == 0.03){
					$time = strtotime("+3 month",$log['vip']);
		 		}else if($data['price'] == 0.06){
					$time = strtotime("+6 month",$log['vip']);
		 		}else if($data['price'] == 0.12){
					$time = strtotime("+12 month",$log['vip']);
		 		}
 			}
	 		
	 		$bool = DB::update("update ims_members set vip = ".$time." ,money = ".$money." where id = ".$data['fid']);
	 		if($bool){
	 			$bool2 = DB::table('paylog')->where('order',$data['order'])->update(array('status'=>1));
	 			if($bool2){
	 				return json_encode(array('r'=>1,'msg'=>'开通会员成功！'));
	 			}else{
	 				return json_encode(array('r'=>1,'msg'=>'开通会员失败！'));
	 			}
	 		}
	 	}else if($data['class'] == '查看会员'){
	 		$uidInfo = (array)DB::table('members')->select('weixin','money')->where('id',$data['uid'])->first();
			$ck_money = ($uidInfo['money']*100+$data['price']*100)/100;
			$_ck_money = $money;
			$wx = $uidInfo['weixin'];

			$log = array(
				'uid'=>$data['uid'],
				'fid'=>$data['fid'],
				'wx'=>$wx,
				'create_time'=>time()
			);
			$bool = DB::table('seewx')->insert($log);
			$bool2 = DB::table('members')->where('id',$data['uid'])->update(array('money'=>$ck_money));
			$bool3 = DB::table('members')->where('id',$data['fid'])->update(array('money'=>$_ck_money));
			if($bool && $bool2 && $bool3){
				$bool4 = DB::table('paylog')->where('order',$data['order'])->update(array('status'=>1));
				if($bool4){
					return json_encode(array('r'=>1,'msg'=>'查看会员成功！'));
				}else{
					return json_encode(array('r'=>1,'msg'=>'查看会员失败！'));
				}
			}
	 	}
    }
}
